﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Mime;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Data.WcfLinq.Helpers;
using DevExpress.Web;
using Newtonsoft.Json;
using TheHeGeo.Util;
using TheHeGeoDao;

namespace TheHeGeo.DataTransfer
{
    public partial class DataStreamForWebChart : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var q = Request.QueryString["r"];
            var d = Request.QueryString["d"];
            if(string.IsNullOrEmpty(q)||string.IsNullOrEmpty(d)) return;
            int duan;
            if(!int.TryParse(d,out duan))  return;
            DataTable dt=null;
            dt = GetDataTableInPageLoad(q, duan);
            var str = DataTableToJson(dt);
            Response.Write(str);  
        }
        protected DataTable GetDataTableInPageLoad(string q, int duan)
        {
            var obj = Session[SessionConst.SES_FLAG_DATA_FOR_WEBCHAR + q] as object[];
            if (obj == null || obj.Length != 3) return null;
            var from = obj[1] as DateTime?;
            var to = obj[2] as DateTime?;
            var ss = DaoHelper.Entities.SensorValues1000.Where(
                p => p.MaSensor == (q) && p.MaDuAn == duan
                && (!from.HasValue || p.ThoiGianDo >= from.Value)
                && (!to.HasValue || p.ThoiGianDo <= to.Value)
                ).OrderByDescending(p => p.ThoiGianDo).Take(100).ToList();
            var dt = new DataTable();
            dt.Columns.Add("ThoiGianDo", typeof(DateTime));
            dt.Columns.Add("GiaTri", typeof(double));
            foreach (var s in ss)
            {
                var dr = dt.NewRow();
                dr[0] = s.ThoiGianDo;
                dr[1] = s.GiaTri;
                dt.Rows.Add(dr);
            }
            return dt;
        }

       

        [WebMethod()]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public void GetData(object obj ,string callback)
        {
            var sb = new StringBuilder();
            sb.Append(callback + "(");
            sb.Append(JsonConvert.SerializeObject(obj, Formatting.Indented)); // indentation is just for ease of reading while testing
            sb.Append(");");

            Context.Response.Clear();
            Context.Response.ContentType = "application/json";
            Context.Response.Write(sb.ToString());
            Context.Response.End();
        }

        public static long ToUnixTimestamp(DateTime target)
        {
            var date = new DateTime(1970, 1, 1, 0, 0, 0);
            
            var unixTimestamp = Convert.ToInt64((target - date).TotalMilliseconds);

            return unixTimestamp;
        }

        public static string DataTableToJson(DataTable table)
        {
            if (table == null) return "";
            var list = new List<object[]>();
//
           for(int i=table.Rows.Count-1;i>=0;i--)
           {
               var row = table.Rows[i];
                var ar = new object[2];
                ar[0] = ToUnixTimestamp((DateTime)row["ThoiGianDo"]);
                ar[1] = row["GiaTri"];
                list.Add(ar);
            }
            var serializer = new JavaScriptSerializer();
            return serializer.Serialize(list);
        }
    }
}